#include <iostream>
#include <cstdio>
#include <string>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int ticket = 0;

// void *active(void *arg)
// {
//     char *id = (char*)arg;
// 	while(1)
// 	{
// 		pthread_mutex_lock(&mutex);
// 		if(ticket > 0)
// 		{
// 			usleep(1000);
// 			printf("%s sells ticket:%d\n",id,ticket);
// 			ticket--;
// 			pthread_mutex_unlock(&mutex);
// 		}
// 		else
// 		{
// 			printf("%s wait on cond!\n",id);
// 			pthread_cond_wait(&cond,&mutex);
// 		}
// 		pthread_mutex_unlock(&mutex);
// 	}
//     return nullptr;
// }

// int main()
// {
//     pthread_t tid1, tid2, tid3, tid4;
//     pthread_create(&tid1, nullptr, active, (void *)"thread-1");
//     pthread_create(&tid2, nullptr, active, (void *)"thread-2");
//     pthread_create(&tid3, nullptr, active, (void *)"thread-3");
//     pthread_create(&tid4, nullptr, active, (void *)"thread-4");


// 	int cnt = 10;
// 	while(1)
// 	{
// 		sleep(5);
// 		printf("主线程放票\n");
// 		ticket += cnt;
// 		pthread_cond_signal(&cond);
// 	}


//     pthread_join(tid1, nullptr);
//     pthread_join(tid2, nullptr);
//     pthread_join(tid3, nullptr);
//     pthread_join(tid4, nullptr);
// }




void *active(void *arg)
{
    std::string name = static_cast<const char *>(arg);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        // 没有对于资源是否就绪的判定
        pthread_cond_wait(&cond, &mutex); // mutex??
        printf("%s is active!\n", name.c_str());
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, nullptr, active, (void *)"thread-1");
    pthread_create(&tid2, nullptr, active, (void *)"thread-2");
    pthread_create(&tid3, nullptr, active, (void *)"thread-3");

    sleep(1);
    printf("Main thread ctrl begin...\n");

    while (true)
    {
        printf("main wakeup thread...\n");
        //pthread_cond_signal(&cond);   // 唤醒单个
        pthread_cond_broadcast(&cond);  // 唤醒全部
        sleep(1);
    }

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
}